package com.sofwin.util;

import org.bytedeco.javacpp.avcodec;
import org.bytedeco.javacpp.opencv_core;
import org.bytedeco.javacv.*;

import javax.swing.*;
import java.io.File;

/**
 * ClassName: com.sofwin.util.CameraRecord
 * Description: 将摄像头的数据转为流或其他文件
 * date: 2021/4/15 11:36 上午
 *
 * @author andyliu
 * @qq 115176513
 * @since JDK 1.8
 */
public class CameraRecord {

    public static void main(String[] args) throws FrameGrabber.Exception, FrameRecorder.Exception, InterruptedException {
        // 创建摄像哦图抓取器的另一种方式，可以自动去寻找查找到的摄像头（已开启）
        FrameGrabber grabber =FrameGrabber.createDefault(0);
        // 开始获取数据
        grabber.start();
        // opencvFrame转换器
        OpenCVFrameConverter.ToIplImage converter = new OpenCVFrameConverter.ToIplImage();
        // 抓取一张图片，等待处理
        opencv_core.IplImage iplImage = converter.convert(grabber.grab());
        // 获取当前图像的宽高
        final int width = iplImage.width();
        final int height = iplImage.height();
        // 创建录像机
        FrameRecorder recorder = FrameRecorder.createDefault(new File("/Users/apple/Downloads/a.mp4"),width,height);

        // 设置编码方式
        recorder.setVideoCodec(avcodec.AV_CODEC_ID_H264);

        // 设置输出格式
        recorder.setFormat("flv");
        // 设置输出帧率
        recorder.setFrameRate(25);
        // 开启录像机
        recorder.start();

        long startTime =0;
        long videoTS = 0;

        CanvasFrame frame = new CanvasFrame("直播窗口");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setAlwaysOnTop(true);
        Frame rotatedFrame = converter.convert(iplImage);
        // 在播放窗口未关闭的情况下开始录制和播放
        while(!frame.isDisplayable() && (iplImage=converter.convert(grabber.grab()))!=null){
            rotatedFrame = converter.convert(iplImage);
            frame.showImage(rotatedFrame);
            if(startTime==0){
                startTime = System.currentTimeMillis();
            }
            videoTS = 1000*(System.currentTimeMillis()-startTime);
            recorder.setTimestamp(videoTS);
            recorder.record(rotatedFrame);
            Thread.sleep(40);
        }
        frame.dispose();
        recorder.close();
        grabber.close();


    }
}
